package org.easy.sse;

import com.alibaba.fastjson.JSON;
import org.easy.sse.dto.EventSourceWriteEventCallback;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSources;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class SseRestTemplate {


    public String postJsonCallback(String url, String token, Object body, EventSourceWriteEventCallback client) {
        String requestBody = "";
        if (body instanceof String) {
            requestBody = (String) body;
        } else {
            requestBody = JSON.toJSONString(body);
        }


        log.info("ssepostJsonCallback  {} {} {}", url, token, requestBody);

        Request.Builder requestBuilder = new Request.Builder().url(url).post(RequestBody.create(MediaType.get("application/json"), requestBody));
        requestBuilder.addHeader("Authorization", "Bearer " + token);

        final CountDownLatch latch = new CountDownLatch(1);
        EventSource.Factory factory = EventSources.createFactory(new OkHttpClient.Builder().build());
        factory.newEventSource(requestBuilder.build(), new EventSourceCallbackListener(client, latch));
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return client.getCompleteData();
    }
}
